import os
import redis
import time
import jwt
from itsdangerous import json

from test_queue import MysqlDb
from functools import reduce
import re
import time
import datetime
import json
import sys

# from test_queue import DelayRedisQueue,get_queue
#
# from tools import clear_last
#
# drq = DelayRedisQueue("myqueue")
#
# while True:
#
#     print("开启延时服务")
#     # print("sb")
#
#     res = drq.pop()
#
#     if res != False:
#
#         drq.remove(res)
#
#         get_queue(clear_last, id=res)
#
#
#     time.sleep(1)


# import random
#
# a = random.randint(1, 5)
# b = random.randint(1, 6)
# print(a, b)


# import redis
#
# rcon = redis.Redis(decode_responses=True)
# rcons = redis.Redis(host='192.168.99.100', port=6380, decode_responses=True)
# key = 'text'
# # rcon.lpush(key, 1)
# # rcons.lpush(key, 2)
# # rcons.lpush(key, 3)
# # rcon.lpush(key, 4)
#
# list1 = rcon.lrange('text', 0, -1)
# list2 = rcons.lrange('text', 0, -1)
# list1 = list1
# for i in list2:
#     list1.append(i)
#
# list1 = [int(i) for i in list1]
# print(list1)

# str1 = ''

# while 1:
# print('嘻嘻')
# print('我恁爹')
#     str1+='嘻嘻'
#     if len(str1) == 10000:
#         break
# print(str1)

# import httpx
# res = httpx.get('https://blog.csdn.net/y472360651/article/details/111313935')
# print(res.cookies)


# x = [1, 2]
# y = [3, 5, 2]
# from test_queue import MysqlDb
# import random
#
# listsss = '2021-12-24'
# hh = listsss[:-2]
#
# mysql = MysqlDb()
# for i in range(1, 31):
#     TIME1 = hh + str(i) + ' 16:17:52'
#
#     TIME2 = hh + str(i)
#     num = random.randint(0, 2)
#     sl = ("insert into `client_stiment` (`uid`,`text`,`stimen`,`date`,`day`) values (28,'真垃圾',%s,'%s','%s')" % (
#     num, TIME1, TIME2))
#
#     mysql.insert(sl)

# import time,datetime
# print(time.time())
#
# print()

# manage_dict = {1: 'Order_1', 2: 'Order_2', 3: 'Order_3'}
# print(manage_dict[1])

# print(20211226194250406%3)


#
# id = '27'
#
# file_list=[{'filename': i, 'type': os.path.splitext(i)[1]} for i in [i for i in os.listdir('./static/') if re.match('\d*',i).group()==id and os.path.splitext(i)[1] in {'.png','.jpg'}]]
#
# print(file_list)


# star = '2021-12-31T15:04'
#
# n = star.split('T')
# time = n[0]+' '+n[1]+':00'
# x = datetime.datetime.strptime(time,'%Y-%m-%d %H:%M:%S')
# print(x,type(x))


# while 1:
#     print('我是你爹,大儿子你好')
# import socket
#
# hostname = socket.gethostname()
# ip = socket.gethostbyname(hostname)
#
# print(ip)


# ad_type = {'2': {'你好': 1, 'title': '日报告'}}

# data = datetime.datetime.now()
#
# now = datetime.datetime.strftime(data, '%Y/%m/%d %H:%M:%S')
# print(now, data)
# print(data + datetime.timedelta(days=1))


# print(datetime.timedelta(days=1))
# x = now+datetime.timedelta(days=1)
# day = datetime.date.today()
# print(day.today() + )
#
# print(str(day.today()) + ad_type['2']['title'])


ad_type = {'type': {'pv': '报告pv', 'uv': '报告uv'},
           'time': {'month': {'sql': "DATE_FORMAT(date,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m')", 'type': '月'},
                    'week': {'sql': "YEARWEEK(DATE_FORMAT(date,'%Y-%m-%d')) = YEARWEEK(NOW())", 'type': '周'},
                    'day': {'sql': "to_days(date) = to_days(now())", 'type': '日'}}}

# print(ad_type['time']['month']['sql'])
# '当%suv图' % name['type']

# print('当%suv图' % ad_type['time']['day']['type'])


#
# print(time.time())
# r = redis.Redis(decode_responses=True)
# list1 = []
# for i in r.keys('celery*'):
# break
# print(r.get(i))
#     r.delete(i)

# res = r.get('celery-task-meta-%s' % '458ebc12-753d-4f49-ab0b-619d394448e4')
#
# print(res)


mysql = MysqlDb()

# res = mysql.read_list("select * from `order_1` where now() > ADDDATE(date, INTERVAL 1 day) and state = 0 union select * from `order_2` where now() > ADDDATE(date, INTERVAL 1 day) and state = 0 union select * from `order_3` where now() > ADDDATE(date, INTERVAL 1 day) and state = 0")
# print(
#     res
# )
# print(res['date'] + datetime.timedelta(days=1) < datetime.datetime.now())
# for i in res:
#     if i['date'] + datetime.timedelta(days=1) < datetime.datetime.now() and i['state'] == 0:
#         print(i)

# sql = ''
# a = ((20211208162811709,),)
# print(a[0])
# print(len(a[0]))
# b = a
# if len(a[0]) == 1:
#     for i in range(3):
#         newa = '(' + str(a[0][0]) + ')'
#         sql += "select * from order_%s where now() > adddate(date,interval 1 day) and state in (1,0) " % (i + 1)
#         if a is not None:
#             sql += "and orderid in %s " % newa
#         sql += "union "
# if len(a[0]) > 1:
#     for i in range(3):
#         sql += "select * from order_%s where now() > adddate(date,interval 1 day) and state in (1,0) " % (i + 1)
#         if a is not None:
#             sql += "and orderid in %s " % str((a[0]))
#         sql += "union "
# sql = sql.rstrip("union ")


# x = str(jwt.encode({'id': 2}, '密钥', algorithm='HS256'), encoding='utf-8')
#
# y = jwt.decode(x, '密钥', algorithms=['HS256'])
# print(y['id'], y)


# print(datetime.datetime.now(), '时间')

# now = datetime.datetime.now()
# delta = datetime.timedelta(days=15)
# n_days = now - delta
#
# print(n_days.strftime('%Y-%m-%d %H:%M:%S'))


# order_list = [{'id': 24, 'orderid': 20220217095137178, 'uid': 1, 'price': 10000, 'date': datetime.datetime(2022, 2, 17, 9, 51, 37), 'state': 0}, {'id': 22, 'orderid': 20220106115314260, 'uid': 1,
#  'price': 8580, 'date': datetime.datetime(2022, 1, 6, 11, 53, 14), 'state': 3}]
#
# for i in order_list:
#     i['orderid'] = str(i['orderid'])
#
# print(order_list)

# c = {'1':5}
# print(c.get('1'))

# print(dir(str))


'''
sorted产生新的地址
列表操作
'''
# list1 = [5, 1, 8, 6, 7]
# print(id(list1))

# x = sorted(list1, reverse=True)
# print(id(x))


# list1.insert(1,1)
#
# print(list1)
# list1[list1.index(8)] = 100
#
# list1.extend(list1)
#
# print(list1)


# b = list1.copy()
# print(id(b),id(list1))
# print(sorted(list1, reverse=True))
# print(list(reversed(list1)))


# fun(list1)
# print(list1)


# x = reduce(fun, list1)
# print(x)


'''
字典操作方法
'''
dict1 = {'x': 1, 'y': 2}

# print(dict1.pop('x'))  # 返回删除该键的值
# print(dict1)
# print(dict1.get('z'))


'''
快排
'''


def kuai(xxx):
    if xxx == []:
        return []
    else:
        a = xxx[0]
        b = kuai([i for i in xxx[1:] if i > a])
        c = kuai([i for i in xxx[1:] if i <= a])

        return b + [a] + c


# print(kuai([5, 10, 6, 2, 3]))


'''
作用域
'''
# s = 0
#
#
# def fun():
#     global s
#     s = 6
#
#
# fun()
# print(s)


'''
re字符串匹配操作/替换等
'''

src = "2021年10月9日，在浙江省第二十一医院内，CT影像设备出现了重要故障，" \
      "造成2021年10月9日到11月21日之间无法正常开展放射检查，所有就诊患者只" \
      "能安排到浙江省第二十二医院接受检查，然后携带检查结果返回第二十一医院进行就诊"

x = re.compile("(.*?年.*?月.*?日)")

new = re.sub("[0-9]", "x", src)
# print(new.replace('第二十一', '某某某A').replace('第二十二', '某某某B'))
#
# print(re.sub(x, "xxxx年xx月xx日", src))


'''
去奇数
'''
list2 = [1, 1, 5, 8, 6, 1, 2]


def func(li):
    if li & 1 == 0:
        return li


# print(list(filter(func, list2)))

# print([i for i in [1, 1, 5, 8, 6, 1, 2] if i & 1 == 0])

'''
去重,但位置不能改变
'''
list3 = [1, 1, 5, 8, 6, 1, 2]


def funv(li):
    dic = {}
    for i in li:
        dic[i] = ''
    return dic


# print(list(funv(list3)))


'''
装饰器返回1,以及打印执行时间
'''


def wrapper(func):
    def inner():
        start = time.time()

        a = func()
        time.sleep(1)
        print(time.time() - start)

        return a

    return inner


@wrapper
def test():
    print('123')
    return '你好'


# print(test())


# @wrapper
# def test1():
#     sum([i for i in range(100000000)])
#
# test1()
#
# @wrapper
# def test2():
#     sum((i for i in range(100000000)))
#
# test2()

'''
生成器和迭代器
大量读写操作/高数据量
'''

'''
三程的应用场景+++++++++++++

cpu密集型任务用进程,进程可以利用系统的多核资源
io密集型任务用线程,线程会受gil全局解释器锁限制

'''


def withs():
    pass


'''
with上下文管理
https://v3u.cn/book/p14.html
'''


def dockers():
    pass


'''
docker 容器式部署命令
挑选基础镜像/考虑大小/我们用的ubuntu/
docker pull 拉取镜像
docker save -o 导出镜像
docker load 导入镜像
docker run 启动容器
docker stop 结束容器进程
docker start 启动
-p 冒号左边是宿主机，右面是容器内
-v  是隐射目录/冒号左边是宿主目录，右面容器内目录
'''

'''
三程使用场景(如何开启start,开始中注意阻塞join,传参args单元素tuple,每个模块用的什么包协程asyncio 线程threading  进程mulitprocessing)
/装饰器/三范式/反三范式/websocket/session-token-cookie/with上下文管理
'''

# withs()
# dockers()


'''
websocket
tornado内置/websockt全双工通信/其他框架都不具备/只有tornado内置websocket协议/直接继承websocket类就可以使用/长连接
第一步，收集连接上的uid/第二步，实现websocket类/websocket长链接根据用户有登录和没登录的
同时有断开操作,用户长时间没有操作或者如果用户关闭页面，链接会关闭/在前端有心跳检测机制
'''

'''
用两个栈实现队列
'''


class Queue:
    def __init__(self):
        self.stockA = []
        self.stockB = []

    def push(self, node):
        self.stockA.append(node)

    def pop(self):
        if self.stockB == []:
            if self.stockA == []:
                return None
            else:
                for i in range(len(self.stockA)):
                    self.stockB.append(self.stockA.pop())
        return self.stockB.pop()


# times = 5
# testList = list(range(times))
# testQueue = Queue()
# for i in range(times):
#     testQueue.push(testList[i])
# print(testList)
# for i in range(times):
#     print(testQueue.pop(), ',', end='')


# print(1 and 2,'1 and 2')
# print(1 or 2,'1 or 2')
# print((1,3) > (1,4),'(1,3) > (1,4)')


'''
递归反转字符串
'''


def reverse(s):
    if s == '':
        return s
    else:
        return reverse(s[1:]) + s[0]


# print(reverse('hello'))

# def col(a, b=[]):
#     b.append(a * 2)
#     print(b)
#
#
# col(1)
# col(2, [])
# col(3)
# col(4, [])

defs = [lambda f: i * 2 for i in range(1, 5)]
def_s = [d(2) for d in defs]
# print(def_s)
# print(defs)

'''
最大的3个数取出最大的积,并且出值
'''
list1 = [1, -5, 2, 106, 3, -7]


class Solution:
    def maximumProduct(self, nums):
        max1, max2, max3 = float('-inf'), float('-inf'), float('-inf')
        min1, min2 = float('inf'), float('inf')

        for num in nums:
            if num > max1:
                max1, max2, max3 = num, max1, max2
            elif num > max2:
                max2, max3 = num, max2
            elif num > max3:
                max3 = num
            if num < min1:
                min1, min2 = num, min1
            elif num < min2:
                min2 = num
        if max1 * max2 * max3 > max1 * min1 * min2:
            return max(max1 * max2 * max3, max1 * min1 * min2), max1, max2, max3
        else:
            return max(max1 * max2 * max3, max1 * min1 * min2), max1, min1, min2


s = Solution()
# print(s.maximumProduct(list1))

# print(9*6*7)

'''
字典根据值排序
'''
key_value = {}

key_value[2] = 56
key_value[1] = 2
key_value[5] = 12
key_value[4] = 24
key_value[6] = 18
key_value[3] = 323

# print(sorted(key_value.items(), key=lambda kv: (kv[1], kv[0]),reverse=True))

# nums = range(2, 20)
# for i in nums:
#
#     nums = filter(lambda x: x == i or x % i, nums)
#     print(list(nums))


'''
一个序列中的连续数字,取连续最长的等差序列 。
'''


class Solution:
    def findLengthOfLCIS(self, nums):
        if not nums:
            return 0

        res = 1  # 初始化结果变量
        cur_len = 1
        ress = []  # 初始化当前连续递增长度
        for i in range(1, len(nums)):
            ress.append(nums[i])  # 遍历
            if nums[i - 1] < nums[i]:  # 如果发现递增对
                cur_len += 1  # 长度+1
                res = max(cur_len, res)  # 更新结果
            else:  # 遇到非递增对
                cur_len = 1  # 重置当前连续递增长度
        return res, ress


solution = Solution()

# print(solution.findLengthOfLCIS([100, 1, 2, 3, 4]))

path1 = os.path.abspath(__file__)

nihao = os.path.dirname(path1)

# print(dir(re))

# print(nihao)
# print(isinstance(path1,))


'''
行转列操作
'''
input = [['姓名', '科目', '分数'],
         ['张三', '数学', 5],
         ['李四', '语文', 3],
         ['张三', '语文', 7],
         ['李四', '音乐', 10],
         ['李四', '数学', 15]
         ]

# for i in input:
#     # print(i)
#     x = []
#     x.append(i[0])
#     for j in i:
#         if j not in x:
#             x.append(j)
#     print(x)


import numpy as np

arr = np.arange(24).reshape(2, 3, 4)
# print(arr)

xx = 'abc'
yy = 'def'
zz = ['d', 'e', 'f']

# print(xx.join(yy))
# print(xx.join(zz))

import pandas as pd

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

df = pd.DataFrame(matrix, columns=list('xyz'), index=list('abc'))


# print(df)
# print(1 ** 2, 2 ** 2, 3 ** 2, 'a行的平方')


class Solution(object):
    def longestPalindrome(self, s):
        List, res_list = [], []
        x = []
        for i in range(len(s)):
            for j in range(len(s), i, -1):
                if s[i:j] == s[i:j][::-1]:
                    List.append(j - i)
                    res_list.append(s[i:j])
        if len(res_list) == 0:
            return ""
        else:
            for i in res_list:
                if len(i) >= 2:
                    x.append(i)
            return x


# a = Solution()
# print(a.longestPalindrome('11235321123'))


class Solutions():
    def longestPalindrome(self, s):

        List, res_list = [], []
        for i in range(len(s)):
            for j in range(len(s), i, -1):
                if s[i:j] == s[i:j][::-1]:
                    List.append(j - i)
                    res_list.append(s[i:j])

        print(res_list)
        if len(res_list) == 0:
            return ""
        else:
            m = List.index(min(List) + 1)
            return res_list[m]


# tests = Solutions()
#
# print(tests.longestPalindrome("11235321123"))


'''
建立一个函数,大于等于2的证书,把它的因子放到一个list中,例子  100 [2,2,5,5]  2*2*5*5单数字不能在分
'''


def funshu(fi):
    xd = list()
    if fi <= 3:
        xd.append(fi)
    if fi >= 4:
        x = 2
        while fi >= x ** 2:
            if fi % x != 0:
                x += 1
            if fi % x == 0:
                xd.append((str(x)))
                fi = int(fi / x)
        xd.append(str(fi))
    if len(xd) == 1 and fi != 1:
        ff = '不能再分了'
        print(ff)
    if fi == 1:
        print('不能分')
    if len(xd) > 1:
        ff = ','.join(xd)
        print(ff)
        return eval(ff)


# time.time()
# for i in range(102):
#     print('这里是数字%s' % i)
#     funshu(i)
# print(2*2*2*3*5)

'''
整数转化二进制   不能使用bin内置函数
'''


def tester(i):
    strleni = len(str(i))
    bitleni = i.bit_length()
    s = ''
    while i:
        s = str(i % 2) + s
        print('%s/2\t%s' % (str(i).rjust(strleni), s.rjust(bitleni, '.')))
        i = i // 2
    print('\n二进制\t%s' % s)


# tester(8)


dic10 = {None: 1, "hello": 2}

# print(dict1.get('nihao'))


# print(sys.getrefcount('a'))   # 查看a的引用次数
# print(sys.getsizeof('a'))     # 查看a的占用内存

# print(dic10[None])

# print('倒着读的是傻逼'[::-1])

'''
请写一个python函数,计算一个2TB文本文件中的大写字母的数量
'''


def chunked_file_reader(fp, block_size=1024 * 3):
    while True:
        chunk = fp.read(block_size)
        if not chunk:
            break
        yield chunk


def funcfile(fname):
    count = 0
    with open(fname, encoding='utf-8') as fs:
        # count = 0
        for i in fs.read():
            if i.isupper():
                count += 1
    return count


# print(funcfile('hello.txt'))


def multipliers():
    return [lambda x: i * x for i in range(4)]


# print([m(3) for m in multipliers()])

# r = redis.Redis(db=2, host='127.0.0.1', port=6379)
#
# r.set(str(time.time()),str(time.time()))


def unique(l):
    d = {}
    for i in l:
        d[i] = 0
    return list(d)


# print(unique([1,3,3,5]))

# print(sorted([1,2,3,5,4]))


def f(n):
    if n <= 4:
        return n * n
    return f(n - 2) + f(n - 3) - f(n - 4) - f(n - 1)


# print(f(100))

# print(filter(lambda x: e / 2 == 0, [e for e in range(10)]))


'''
一个班级表,一个id,一个name,找到名字相同的,找到两个以上相同的group by 分组名 having count(1) > 1
'''
# select count(1),name from `表名` group by name having count(1) > 1